package com.zk.config.api.factory;

import java.util.Enumeration;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import com.zk.config.api.client.ConfigClient;
import lombok.Setter;

public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer implements FactoryBean<Properties>{

	@Setter
	private ConfigClient[] configClient;
	private Properties singletonInstance;

	@Override
	public Properties getObject() throws Exception {
		if (this.singletonInstance == null) {
			this.singletonInstance = new Properties();
		}
		return this.singletonInstance;
	}

	@Override
	public Class<?> getObjectType() {
		return Properties.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactory,
			Properties props)throws BeansException {
		if (props != null && singletonInstance != null) {
			Enumeration en;
			for (en = props.propertyNames(); en.hasMoreElements();) {
				String key = (String) en.nextElement();
				if(this.localOverride) {
					if(!singletonInstance.containsKey(key)) {
						singletonInstance.put(key, props.getProperty(key));
					}
				} else {
					singletonInstance.put(key, props.getProperty(key));
				}
			}
		}
		if(singletonInstance != null) {
			props.clear();
			props = singletonInstance;
		}
		super.processProperties(beanFactory, props);
	}
}